import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import Icons from 'unplugin-icons/vite'
import IconsResolver from 'unplugin-icons/resolver'
import { FileSystemIconLoader } from 'unplugin-icons/loaders'
import UnoCSS from 'unocss/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'node:path'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    UnoCSS(),
    createSvgIconsPlugin({
      // 指定图标目录
      iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
      // 自定义图标ID
      symbolId: 'icon-[dir]-[name]',
      // 存放位置
      inject: 'body-last',
      customDomId: '__svg__icon_dom__',
    }),
    AutoImport({
      resolvers: [
        IconsResolver({
          prefix: 'icon',
        }),
      ],
      imports: [
        'vue',
        'vue-router',
        'pinia',
        {
          'naive-ui': [
            'useDialog',
            'useMessage',
            'useNotification',
            'useLoadingBar',
          ],
        },
      ],
      dts: './auto-imports.d.ts',
      include: [/\.vue$/, /\.vue\?vue/, /\.md$/, /\.ts$/, /\.js$/],
      dirs: ['src/hooks', 'src/stores'],
      vueTemplate: true,
    }),
    Components({
      dts: true,
      resolvers: [
        NaiveUiResolver(),
        IconsResolver({
          enabledCollections: ['ep', 'ic', 'material-symbols-light'],
          customCollections: ['custom'],
        }),
      ],
      dirs: ['src/components', 'src/views/*/components'],
      extensions: ['vue', 'ts'], // 指定文件扩展名
      deep: true, // 是否递归子目录
      directoryAsNamespace: true, // 是否将目录名作为命名空间
    }),
    Icons({
      // 自动安装
      autoInstall: true,
      //自定义图标集合
      customCollections: {
        // 加载目录下的所有svg文件
        custom: FileSystemIconLoader('src/assets/icons', svg =>
          svg.replace(/^<svg /, '<svg fill="currentColor" '),
        ),
      },
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
      // node_modules: fileURLToPath(new URL('./node_modules', import.meta.url)),
    },
  },
  server: {
    hmr: true,
    port:5174,
    proxy:{
      '/api': {
        target: 'http://127.0.0.1:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
})
